package mm.chenchen.modules.sys.service.impl;

import mm.chenchen.common.constant.SeqConstant;
import mm.chenchen.constant.ResultMsg;

import mm.chenchen.db.annotation.DataSource;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import mm.chenchen.utils.R;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import mm.chenchen.modules.sys.entity.FastStartSeq;
import mm.chenchen.modules.sys.dao.FastStartSeqDao;
import mm.chenchen.modules.sys.service.FastStartSeqService;
import mm.chenchen.utils.PageUtils;
import mm.chenchen.utils.PageModel;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import mm.chenchen.modules.sys.dao.model.request.FastStartSeqQuery;
import org.springframework.util.ObjectUtils;


@Service("fastStartSeqService")
////@DataSource("base")
public class FastStartSeqServiceImpl extends ServiceImpl<FastStartSeqDao, FastStartSeq> implements FastStartSeqService {


    public R findPage(Page<Map> page, FastStartSeqQuery param) {
        IPage<FastStartSeq> pageData = baseMapper.findPage(page, param);
        if (pageData != null) {
            return R.ok().setData(new PageModel(pageData.getRecords(), pageData.getTotal(), pageData.getSize(), pageData.getCurrent()));
        } else {
            return R.error(ResultMsg.DATA_NOT_EXIT);
        }
    }

    public R getById(Integer id) {
        return R.ok().setData(super.getById(id));
    }

    ;

    public R saveInfo(FastStartSeq param) {
        param.setId(nextVal(SeqConstant.SEQ_ID_NAME));
        param.setCreateTime(new Date());
        return R.ok().setData(super.save(param));
    }

    public R update(FastStartSeq param) {
        FastStartSeq data = super.getById(param.getId());
        if (ObjectUtils.isEmpty(data)) {
            return R.error(ResultMsg.DATA_NOT_EXIT);
        }
        param.setUpdateTime(new Date());
        return R.ok().setData(super.updateById(param));
    }

    public R deleteById(String id) {
        if (ObjectUtils.isEmpty(id)) {
            return R.error(ResultMsg.DATA_NOT_EXIT);
        }
        String[] ids = id.split(",");
        List<Integer> intIds = new ArrayList<>();
        for (String s : ids) {
            intIds.add(Integer.parseInt(s));
        }
        return R.ok().setData(super.removeByIds(intIds));
    }

    public int nextVal(String name) {

        int x = baseMapper.nextVal(name);
        if (ObjectUtils.isEmpty(x) || x == 0) {
            FastStartSeq param = new FastStartSeq();
            param.setSeqName(name);
            param.setIncrementVal(1);
            param.setCurrentVal(100000);
            saveInfo(param);
            x = baseMapper.nextVal(name);
        }
        return x;
    }

}